<template>
    <div class="header_avatar">
        <el-upload
        class="upload"
        ref="upload"
        action=""
        :auto-upload="false"
        :show-file-list="false"
        :on-change="onUploadFile"
        :before-upload="beforeAvatarUpload">
            <el-avatar :size="120" fit="cover"
            v-if="avatarUrl ? avatarUrl : getAvatar"
            :src="avatarUrl ? avatarUrl : getAvatar">
            </el-avatar>
            <el-avatar :size="120" v-else class="el-icon-plus avatar-uploader-icon"></el-avatar>
        </el-upload>
        <el-button
        size="small"
        type="primary"
        icon="el-icon-plus"
        @click="$refs.upload.$el.querySelector('input').click()">
        选择图片
        </el-button>
        <el-button size="small" type="success" icon="el-icon-upload2" @click="onUpload">上传图片</el-button>
    </div>
</template>

<script>
import { Message } from 'element-ui'
import { uploadAvatarService } from '@/api/user'
import { uploadMAvatarService } from '@/api/maintainer'
import { mapGetters } from 'vuex'
export default {
  data () {
    return {
      avatarUrl: ''
    }
  },
  created () {
    this.seturl()
  },
  methods: {
    seturl () {
      const partten = /^\/use\//.test(this.$route.path)
      if (partten) {
        this.avatarUrl = this.getAvatar
      } else {
        this.avatarUrl = this.getMAvatar
      }
    },
    onUploadFile (uploadFile) {
      // 图片预览
      this.avatarUrl = URL.createObjectURL(uploadFile.raw)

      // 基于 FileReader 读取图片预览
      const reader = new FileReader()
      reader.readAsDataURL(uploadFile.raw)

      reader.onload = () => {
        this.uploadUrl = reader.result
      }

      reader.onerror = (error) => {
        Message.error('读取文件失败' + error)
      }
    },
    async onUpload () {
      if (!this.uploadUrl) return Message.error('上传失败，请选择图片')
      const partten = /^\/user\//.test(this.$route.path)
      if (partten) {
        await uploadAvatarService(this.uploadUrl)
        await this.$store.dispatch('userStore/getBaseInfoService')
      } else {
        await uploadMAvatarService(this.uploadUrl)
        await this.$store.dispatch('maintainerStore/getMaintainerInfoService')
      }
      await Message.success('上传头像成功')
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        Message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        Message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  },
  computed: {
    ...mapGetters('userStore', ['getAvatar']),
    ...mapGetters('maintainerStore', ['getMAvatar'])
  }
}
</script>

<style lang="less" scoped>

</style>
